package com.fenrirtec.aepp.manage.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.fenrirtec.aepp.manage.common.definition.Definition;

public class LoginCheckFilter_JSON implements Filter {

	private static final Logger logger = LoggerFactory.getLogger(LoginCheckFilter_JSON.class);

	@Override
	public void init(FilterConfig config) throws ServletException {
	}

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain child) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		HttpSession session = request.getSession(false);
		if (session == null) {
			if (logger.isTraceEnabled()) {
				logger.trace("request does not have session.");
			}
			sendError(response);
		} else if (session.getAttribute(Definition.SessionKey.USER_INFO) == null) {
			if (logger.isTraceEnabled()) {
				logger.trace("request does not have session. key={}", Definition.SessionKey.USER_INFO);
			}
			sendError(response);
		} else {
			child.doFilter(request, response);
		}
	}

	private void sendError(HttpServletResponse response) {
		PrintWriter writer = null;
		try {
			response.setContentType(Definition.JSON.CONTENT_TYPE);
			response.setCharacterEncoding(Definition.JSON.ENCODING);
			writer = response.getWriter();
			JSONObject root = new JSONObject();
			root.put(Definition.API.Common.Response.STATUS, Definition.API.Common.Status.LOGIN_ERROR);
			writer.write(root.toString());
			writer.flush();
		} catch (IOException e) {
		}
	}

}
